import requests
from urllib.parse import urlencode
from settings.config import config
import json
import uuid
import os


def query_music(keyword):
    url = 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp'
    params = {
        'ct': 24,
        'qqmusic_ver': 1298,
        'new_json': 1,
        'emoteplace': 'txt.yqq.center',
        'searchid': 53974321492458513,
        't': 0,
        'aggr': 1,
        'cr': 1,
        'catZhida': 1,
        'lossless': 0,
        'flag_qc': 0,
        'p': 1,
        'n': 10,
        'w': keyword,
        'g_tk': 5381,
        'jsonpCallback': 'MusicJsonCallback10824288779325952',
        'loginUin': 0,
        'hostUin': 0,
        'format': 'json',
        'inCharset': 'utf8',
        'outCharset': 'utf-8',
        'notice': 0,
        'platform': 'yqq',
        'needNewCode': 0
    }
    resp = requests.get(url, params=params, verify=False)
    result = resp.json()
    result_list = []
    print('query_music result', result)
    try:
        music_list = result.get('data', dict()).get('song', dict()).get('list', list())
        current_music = music_list[:7]
        for _ in current_music:
            singer_name = ''
            singer = _.get('singer', [])
            if singer and (len(singer) > 0):
                singer_name = singer[0].get('name', '')
            song_mid = _.get('mid', '')
            album_id = _.get('album', '') and _.get('album', dict()).get('mid', '')
            song_name = _.get('title', '')
            song_desc = _.get('subtitle', '')
            song_id = _.get('id', '')
            result_list.append({
                "singer_name": singer_name,
                "song_mid": song_mid,
                "album_id": album_id,
                "song_name": song_name,
                "song_desc": song_desc,
                "song_id": song_id
            })
    except Exception:
        pass
    return result_list


def get_song_info(song_id):
    pass


def get_album_thumb(album_id):
    print('1', album_id)
    n = '300'
    o = 'T002'
    if len(album_id) >= 14:
        thumb_url = '/photo_new/' + o + 'R' + n + 'x' + n + 'M000' + album_id + '.jpg?max_age=2592000'
    else:
        thumb_url = '/photo/' + o + '_' + n + '/' + str(int(album_id) % 100)\
                    + '/' + n + '_' + o + 'pic_' + str(album_id) + '_0.jpg?max_age=2592000'
    return 'https://y.gtimg.cn/music' + thumb_url


def get_song_key(song_mid):
    callback_key = 'getplaysongvkey725539600059133'
    url = "https://u.y.qq.com/cgi-bin/musicu.fcg?"
    params = {
        "g_tk": 5381,
        "loginUin": 0,
        "hostUin": 0,
        "format": "json",
        "inCharset": "utf8",
        "outCharset": "utf8",
        "notice": 0,
        "platform": 'yqq',
        "needNewCode": 0,
        "callback": callback_key,
        "jsonpCallback": callback_key,
        "data": json.dumps({
            "req": {"module": "CDN.SrfCdnDispatchServer", "method": "GetCdnDispatch",
                    "param": {"guid": "6501846271", "calltype": 0, "userip": ""}},
            "req_0": {
                "module": "vkey.GetVkeyServer",
                "method": "CgiGetVkey",
                "param": {
                    "guid": "6501846271",
                    "songmid": [song_mid],
                    "songtype": [0],
                    "uin": "0",
                    "loginflag": 1,
                    "platform": "20"
                }
            },
            "comm": {
                "uin": 0,
                "format": "json",
                "ct": 20,
                "cv": 0
            }
        })
    }
    params_str = urlencode(params)
    url += params_str
    url = url.replace('+', '')
    resp = requests.get(url=url, verify=False)
    song_url = []
    sip = []
    try:
        resp_json_text = resp.text.replace(callback_key + '(', '')
        resp_json_text = resp_json_text[:-1]
        resp_json = json.loads(resp_json_text)
        if resp_json.get('code', None) == 0:
            song_url = resp_json.get('req_0', dict()).get('data', dict()).get('midurlinfo', list())
            song_url = [_.get('purl', '') for _ in song_url]
            sip = resp_json.get('req', dict()).get('data', dict()).get('sip', list())
    except Exception:
        print('Exception get_song_key')
        resp_json = dict()
    # print('resp_json', resp_json)
    # info = dict()
    # info['url'] = song_url
    # info['sip'] = sip
    real_url = ''
    if len(sip) > 0 and sip[0] != '' and len(song_url) > 0 and song_url[0] != '':
        real_url = sip[0] + song_url[0]

    # print('info', info)
    return real_url


def get_lyric(song_id, song_mid):
    callback_key = 'jsonp1'
    url = 'https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric.fcg'
    params = {
        "musicid": song_id,
        "g_tk": 5381,
        "nobase64": 1,
        "loginUin": 0,
        "hostUin": 0,
        "format": "jsonp",
        "inCharset": "utf8",
        "outCharset": "utf8",
        "notice": 0,
        "platform": 'yqq',
        "needNewCode": 0,
        "callback": callback_key,
        "jsonpCallback": callback_key
    }
    headers = {'referer': 'https://y.qq.com/n/yqq/song/' + song_mid + '.html'}
    resp = requests.get(url=url, headers=headers, params=params, verify=False)
    try:
        resp_json_text = resp.text.replace(callback_key + '(', '')
        resp_json_text = resp_json_text[:-1]
        resp_json = json.loads(resp_json_text)
    except Exception:
        resp_json = dict()
    return resp_json.get('lyric', '')


def download_file(tp, url):
    print('download start')
    resp = requests.get(url=url, verify=False)
    file_name = get_file_name(tp)
    with open(file_name.get('full_path'), 'wb') as code:
        code.write(resp.content)
    print('download end')
    return file_name


def get_file_name(tp):
    music_path = os.path.join(config.APP_ROOT, 'music')
    random = str(uuid.uuid4())
    if tp == 'audio':
        return {
            'full_path': os.path.join(music_path, 'audio/' + str(random) + '.mp3'),
            'server_path': 'music/audio/' + random + '.mp3'
        }
    elif tp == 'image':
        return {
            'full_path': os.path.join(music_path, 'image/' + str(random) + '.jpg'),
            'server_path': 'music/image/' + random + '.jpg'
        }

